﻿using Zbk_shop.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Zbk_shop.Service
{
    public class JWTService:IJWTService
    {
        private readonly JWTConfig _jwtConfig;

        public JWTService(IOptions<JWTConfig> jwtConfig)
        {
            this._jwtConfig = jwtConfig.Value;
        }
        /// <summary>
        /// 创建令牌的过程
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public string CreateToken(string userId,string mobile)
        {
            //把有需要的信息写到Token
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(ClaimTypes.MobilePhone, mobile),
            };

            //创建密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.Secret));
            //密钥加密
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //token配置
            var jwtToken = new JwtSecurityToken(_jwtConfig.Issuer,
                _jwtConfig.Audience,
                claims,
                expires: DateTime.Now.AddMinutes(_jwtConfig.AccessExpiration),
                signingCredentials: credentials);

            //获取token
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return token;
        }
    }
}
